package com.dingding.util;

import com.common.util.DateUtil;
import com.dingding.config.Constant;
import com.dingding.config.URLConstant;
import com.dingding.model.TokenVo;
import com.dingtalk.api.DefaultDingTalkClient;
import com.dingtalk.api.request.OapiGettokenRequest;
import com.dingtalk.api.response.OapiGettokenResponse;
import com.taobao.api.ApiException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * 获取access_token工具类
 */
@Service
public class AccessTokenUtil {
    private static final Logger bizLogger = LoggerFactory.getLogger(AccessTokenUtil.class);

    public static Map<String, TokenVo> tokenMap = new HashMap<>();

    public String getToken() throws RuntimeException {
        try {
            DefaultDingTalkClient client = new DefaultDingTalkClient(URLConstant.URL_GET_TOKKEN);
            OapiGettokenRequest request = new OapiGettokenRequest();

            request.setAppkey(Constant.APPKEY);
            request.setAppsecret(Constant.APPSECRET);
            request.setHttpMethod("GET");
            OapiGettokenResponse response = client.execute(request);
            String accessToken = response.getAccessToken();
            return accessToken;
        } catch (ApiException e) {
            bizLogger.error("getAccessToken failed", e);
            throw new RuntimeException();
        }

    }

    /**
    * @Description: 根据公司获取token
    * @Param: [key]
    * @return: java.lang.String
    * @Author: zyj
    * @Date: 2020/3/10
    */
    public String getToken(String key){
        Date date = DateUtil.getNowHourAfter(1);
        Date now = new Date();
        TokenVo tokenVo = tokenMap.get(key);

        //新token
        if(null == tokenVo){
            String token = getToken();
            TokenVo tokenVo1 = new TokenVo();
            tokenVo1.setToken(token);
            tokenVo1.setOverTime(date);
            System.out.println("token:"+token);
            tokenMap.put(key, tokenVo);
            return token;
        }

        //判断是否超期
        Date dateOver = tokenVo.getOverTime();
        if(dateOver.before(now)){
            String token = getToken();
            TokenVo tokenVo1 = new TokenVo();
            tokenVo1.setToken(token);
            tokenVo1.setOverTime(date);

            tokenMap.put(key, tokenVo);
            return token;
        }

        return tokenVo.getToken();
    }
}
